package isssr.control.src;

import isssr.dao.exception.DAOException;
import isssr.dao.factory.DAOFactory;
import isssr.dao.factory.DAOFactoryType;
import isssr.dao.interfaces.OrganizationalGoalDAO;
import isssr.dao.interfaces.RecordPagination;
import isssr.dao.interfaces.RecordSorting;
import isssr.entity.src.GoalStatus;
import isssr.entity.src.OrganizationalGoal;
import isssr.entity.src.OrganizationalGoalDTO;
import isssr.entity.src.Perspective;
import isssr.entity.src.User;
import isssr.entity.src.UserContext;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import org.primefaces.model.SortOrder;


@ManagedBean(name="organizationalGoalFinderControl")
@ViewScoped
public class OrganizationalGoalFinderControl  implements Serializable  {

	private static final long serialVersionUID = 7770624415429750380L;
	
	@ManagedProperty(value="#{userContext}")
	private UserContext currentContext; 

	private final static String[] 	states;

	static{	
		GoalStatus[] possible_states =  GoalStatus.values();
		states = new String[possible_states.length];
		for(int i=0; i<possible_states.length; i++)
			states[i] = possible_states[i].name();	
	}
	
	
	public OrganizationalGoalFinderControl(){
		System.out.println("entry in finder control");
	}

	
	public void setCurrentContext(UserContext currentContext) {
		this.currentContext = currentContext;
	}
	
/*
	@Override  
    public Object getRowKey(OrganizationalGoal goal) {  
        return goal.getId();  
    }
	
	@Override  
    public OrganizationalGoal getRowData(String rowKey) {  
		
		Integer goalID;
		
		for(OrganizationalGoal goal : this.fetchedGoal) {  
            
			goalID = Integer.parseInt(rowKey);
			
			if(goal.getId().equals(goalID))  
			{
				return goal;  
			}  
		}
        return null;  
    }  
*/	


	@SuppressWarnings("finally")
	public int load(int firstRecord, int pageSize, String sortField, SortOrder sortOrder,
			Map<String, String> filters, List<OrganizationalGoalDTO> resultList) {
			
		System.out.println("entry in load control");

		
		// set pagination
		RecordPagination pagination = new RecordPagination();
		pagination.firstResult 		= firstRecord;
		pagination.pageSize			= pageSize;
		
		// set sort order
		RecordSorting sorting = this.setRecordSorting(sortField, sortOrder);
		
		// fetch results
		DAOFactory factory = DAOFactory.getDAOFactory(DAOFactoryType.HIBERNATE);
		OrganizationalGoalDAO goalDao = factory.getOrganizationalGoalDAO();
		
		// set actor
		User actor = this.currentContext.getUser();
		Perspective view_type = this.currentContext.getView();
		
		Map<String, Object> filtersMap = this.castStringMapToObjectMap(filters);
		
		List<OrganizationalGoal> tempList = new ArrayList<OrganizationalGoal>();
		int resultNumber = 0;
		
		try{	
			switch (view_type) {
				case OWNER_VIEW:
					resultNumber = goalDao.getAllByOwner(tempList, actor, filtersMap, sorting, pagination);
					break;
				case SUPER_OWNER_VIEW:
					resultNumber = goalDao.getAllBySuper(tempList, actor, filtersMap, sorting, pagination);
				case ENACTOR_VIEW:
					resultNumber = goalDao.getAllByEnactor(tempList, actor, filtersMap, sorting, pagination);
					break;
				default:
					break;
			}
			
			for(int i=0; i<tempList.size(); i++)
			{
				OrganizationalGoal retrievedGoal = tempList.get(i);
				OrganizationalGoalDTO goalData = retrievedGoal.getDTO();
				resultList.add(goalData);
			}
		}
		catch (DAOException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
			System.out.println("generic ex");
		}
		
		finally {
			return resultNumber;
		}
		
	}
	
	
	private RecordSorting setRecordSorting(String sortField, SortOrder sortOrder) {
		
		RecordSorting.SortOrder ordering;
	
		switch (sortOrder) {
		case ASCENDING:
			ordering = RecordSorting.SortOrder.ASCENDING;
			break;
		case DESCENDING:
			ordering = RecordSorting.SortOrder.DESCENDING;
			break;
		default:
			ordering = RecordSorting.SortOrder.UNSORTED;
			break;
		}
		
		return new RecordSorting(sortField, ordering);
	}
	
	
	private Map<String, Object> castStringMapToObjectMap(Map<String, String> stringMap) {
		Map<String, Object> objectMap = new HashMap<>();
		try
		{
			System.out.println("entry in cast map");
			for(Map.Entry<String, String> entry : stringMap.entrySet())
			{
				String key 		= entry.getKey();
				Object value	= null;
				
			
				if(key.equals("status"))
				{
					for(int i=0; i<states.length; i++)
					{
						if(states[i].equals(entry.getValue()))
						{
							value = GoalStatus.valueOf(states[i]);
							System.out.println("status:\t"+value);
						}	
					}
				}
				else
					value = (Object) entry.getValue(); 
				objectMap.put(key, value);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("exit in cast map");
		return objectMap;
	}
	
}
